package com.meida.app.provider.configuration;

import com.meida.common.constants.CommonConstants;
import com.meida.common.utils.RedisUtils;
import com.meida.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 验证是否需要登录
 *
 * @author zyf
 */
@Slf4j
@Component
public class MyAuthorizationManager {

    @Autowired
    private RedisUtils redisUtils;

    public boolean check(HttpServletRequest request, Authentication authentication) {

        Map<Object, Object> notAuthList = redisUtils.getMapByProject(CommonConstants.NOTAUTH_KEY + CommonConstants.APP_SERVICE);
        String requestPath = getRequestPath(request);
        if (notAuthList.containsValue(requestPath)) {
            return true;
        } else {
            if (!authentication.getPrincipal().toString().equals("anonymousUser")) {
                return true;
            } else {
                return false;
            }
        }
    }

    public String getRequestPath(HttpServletRequest request) {
        String url = request.getServletPath();
        String pathInfo = request.getPathInfo();
        if (pathInfo != null) {
            url = StringUtils.isNotBlank(url) ? url + pathInfo : pathInfo;
        }
        return url;
    }

}
